package com.zzyl.nursing.service.impl;

import cn.hutool.core.util.ObjectUtil;
import cn.hutool.http.HttpUtil;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.zzyl.nursing.service.WechatService;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.Map;

@Service
public class WechatServiceImpl implements WechatService {

    private static final String openIdUrl="https://api.weixin.qq.com/sns/jscode2session";

    private static final String tokenUrl="https://api.weixin.qq.com/cgi-bin/token";

    private static  final  String phoneUrl="https://api.weixin.qq.com/wxa/business/getuserphonenumber?access_token=";



    @Value("${wechat.appId}")
    private String appid;

    @Value("${wechat.appSecret}")
    private String secret;
    /**
     * 获取openid
     *
     * @param code
     * @return
     */
    @Override
    public String getOpenid(String code) {
        Map<String, Object> params = new HashMap<String, Object>();
        params.put("appid", appid);
        params.put("secret", secret);
        params.put("js_code", code);
        params.put("grant_type", "authorization_code");

        String result = HttpUtil.get(openIdUrl, params);

        JSONObject jsonObject = JSONUtil.parseObj(result);
        // 判断接口响应是否出错
        if(ObjectUtil.isNotEmpty(jsonObject.getInt("errcode"))) {
            throw new RuntimeException(jsonObject.getStr("errmsg"));
        }
        return jsonObject.getStr("openid");
    }

    private String getToken() {
        Map<String, Object> params = new HashMap<String, Object>();
        params.put("appid", appid);
        params.put("secret", secret);
        params.put("grant_type", "client_credential");
        String result = HttpUtil.get(tokenUrl, params);
        JSONObject jsonObject = JSONUtil.parseObj(result);
        return jsonObject.getStr("access_token");
    }

    /**
     * 获取手机号
     *
     * @param detailCode 手机号code
     * @return
     */
    @Override
    public String getPhone(String detailCode) {
        String url=phoneUrl+getToken();
        Map<String, Object> params=new HashMap<>();
        params.put("code",detailCode);
        String result = HttpUtil.post(url, JSONUtil.toJsonStr(params));

        JSONObject jsonObject = JSONUtil.parseObj(result);
        // 判断接口响应是否出错
        if(jsonObject.getInt("errcode") != 0) {
            throw new RuntimeException(jsonObject.getStr("errmsg"));
        }
        String phone = jsonObject.getJSONObject("phone_info").getStr("phoneNumber");
        return phone;
    }
}
